<template>
  <el-dialog v-model="dialogVisible" title="出售商品" width="600px">
    <el-form :model="formData" label-width="100px" ref="formRef">
      <el-form-item label="商品图片" prop="productCoverImage" required>
        <el-upload
          action="#"
          :auto-upload="false"
          :on-change="handleFileChange"
          :show-file-list="false"
          accept=".png,.jpg,.jpeg,.gif"
        >
          <el-button type="primary">点击上传</el-button>
          <template #tip>
            <div class="el-upload__tip">支持PNG/JPG/GIF格式，大小不超过10MB</div>
          </template>
        </el-upload>
      </el-form-item>

      <el-form-item label="商品名称" prop="productName" required>
        <el-input v-model="formData.productName" placeholder="请输入商品名称" />
      </el-form-item>

      <el-form-item label="商品描述" prop="productDescription">
        <el-input
          v-model="formData.productDescription"
          type="textarea"
          :rows="3"
          placeholder="请输入商品描述"
        />
      </el-form-item>

      <el-form-item label="商品价格" prop="productPrice" required>
        <el-input
          v-model="formData.productPrice"
          type="number"
          placeholder="请输入商品价格"
          :min="0"
        >
          <template #append>元</template>
        </el-input>
      </el-form-item>

      <el-form-item label="商品库存" prop="productStock" required>
        <el-input
          v-model="formData.productStock"
          type="number"
          placeholder="请输入库存数量"
          :min="0"
        />
      </el-form-item>

      <el-form-item label="商品分类" prop="categoryId" required>
        <el-select
          v-model="formData.categoryId"
          placeholder="请选择分类"
          filterable
        >
          <el-option
            v-for="category in categories"
            :key="category.category_id"
            :label="category.category_name"
            :value="category.category_id"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitForm">立即出售</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage, type UploadFile } from 'element-plus'
import axios from 'axios'

const emit = defineEmits(['success'])
const formRef = ref()

const dialogVisible = ref(false)
const categories = ref<Array<{category_id: number, category_name: string}>>([])
const formData = reactive({
  productCoverImage: undefined as File | undefined,
  productName: '',
  productDescription: '',
  productPrice: '',
  productStock: 0,
  categoryId: undefined as number | undefined
})

// 获取分类列表
const fetchCategories = async () => {
  try {
    const response = await axios.get(`${import.meta.env.VITE_API_BASE}/product/category`)
    categories.value = response.data
  } catch (error) {
    ElMessage.error('获取分类失败')
  }
}

// 文件选择处理
const handleFileChange = (file: UploadFile) => {
  formData.productCoverImage = file.raw!
}

// 表单验证
const rules = {
  productName: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  productPrice: [
    { required: true, message: '请输入商品价格', trigger: 'blur' },
    { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入有效金额格式', trigger: 'blur' }
  ],
  productStock: [
    { required: true, message: '请输入库存数量', trigger: 'blur' },
    { type: 'number', min: 0, message: '库存不能小于0', trigger: 'blur' }
  ],
  categoryId: [{ required: true, message: '请选择商品分类', trigger: 'change' }]
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()
    
    if (!formData.productCoverImage) {
      ElMessage.error('请上传商品图片')
      return
    }

    const form = new FormData()
    form.append('productCoverImage', formData.productCoverImage)
    
    
    const productInfoBlob = new Blob([JSON.stringify({
      productName: formData.productName,
      productDescription: formData.productDescription,
      productPrice: formData.productPrice,
      productStock: formData.productStock,
      categoryId: formData.categoryId
    })], { type: 'application/json' })
    
    form.append('productInfo', productInfoBlob, 'productInfo.json')

    const response = await axios.post(
      `${import.meta.env.VITE_API_BASE}/product`, 
      form,
      {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      }
    )

    ElMessage.success('商品发布成功！')
    dialogVisible.value = false
    emit('success')
  } catch (error) {
    ElMessage.error('商品发布失败')
  }
}

// 打开弹窗时加载分类
const openDialog = () => {
  dialogVisible.value = true
  fetchCategories()
}

defineExpose({
  openDialog
})
</script>